import cooApp, {
    ui,
    Widget,
    basicWidgets,
    coolink,
    cooInfo,
    Util
} from 'coolink-ts'
import { Colors } from '../config'
import func, { px } from '../base/func'
import Center from '../widgets/Center'
import baseInfo from '../base/baseInfo'
import { showAutoHideToast } from '../widgets/Toast'

const {
    Page,
    AppBar,
    Container,
    Text,
    Image,
    AudioView,
    Button
} = basicWidgets

export default class AudioPage extends Widget<any, any> {

    state = {
        // 通用数据
        playUrls: ['http://img.sky.fs.skysrt.com/music/1_1.mp3', 'http://img.sky.fs.skysrt.com/music/1_0_3.mp3', 'http://img.sky.fs.skysrt.com/music/1_0_4.mp3'],
        curIndex: 0,
        curPalyUrl: 'http://img.sky.fs.skysrt.com/music/1_1.mp3',
        audiobgImgs: ['https://beta-webapp.skysrt.com/lxw/market/img/4k-1.jpg', 'https://beta-webapp.skysrt.com/lxw/market/img/4k-2.jpg', 'https://beta-webapp.skysrt.com/lxw/market/img/4k-3.jpg'],
        // 手机端数据
        autoPlay: true,
        loopPlay: false,
        duration: 0,
        position: 0,
        playStatus: 1,

        // TV端数据
        curPalyUrl_tv: 'http://img.sky.fs.skysrt.com/music/1_1.mp3',
        autoPlay_tv: true,
        loopPlay_tv: false,
        duration_tv: 0,
        position_tv: 0,
        playStatus_tv: 1,

        // 界面样式
        backgroundGradient: {
            colors: [0xFF9C04D0, 0xFFFF60D5],
            type: 'linear',
            begin: 'centerLeft',
            end: 'centerRight'
        },
        boxShadow: {
            color: Colors.Black,
            blurRadius: 24,
            spreadRadius: 0,
        },
    }
    audioRef: any;
    audioRef_tv: any;



    widgetDidMount() {
        cooApp.pageDidShow();
        // 开启组件联动
        this.enableLinking('my-homepage-component');
        this.setLinkCommandCallback(this.linkCommandProcess.bind(this));

        if (!this.isTv()) {
            //this.showAwardsInPhone();
        } else {
            this.sendLinkCommand({ cmd: 'tv-ready' });
        }
    }

    constructor(props: any) {
        super(props);
        props.onHide = this.onHide.bind(this);
        props.onShow = this.onShow.bind(this);
    }
    onHide() {
        Util.warn('lxw onHide:');
    }
    onShow() {
        Util.warn('lxw onShow:');
        // 想继续播，再次点击播放就可以了
        // setTimeout(() => {
        //     if (this.isTV()) {
        //         this.setTvState({ playStatus_tv: 1 });
        //         this.audioRef_tv.play();
        //     } else {
        //         this.setTvState({ playStatus: 1 });
        //         this.audioRef.play();
        //     }
        // }, 20)
    }
    onPause() {
        Util.warn('lxw onPause:');
        setTimeout(() => {
            if (this.isTV()) {
                this.setTvState({ playStatus_tv: 0 });
                this.audioRef_tv.pause();
            } else {
                this.setState({ playStatus: 0 });
                this.audioRef.pause();
            }
        }, 20)
    }
    onResume() {
        Util.warn('lxw onResume:');
        setTimeout(() => {
            if (this.isTV()) {
                this.setTvState({ playStatus_tv: 1 });
                this.audioRef_tv.play();
            } else {
                this.setTvState({ playStatus: 1 });
                this.audioRef.play();
            }
        }, 20)
    }

    widgetDidUpdate(): void {

    }
    widgetDidUnmount(): void {
        Util.warn('lxw widgetDidUnmount:');
        if (this.isTV()) {
            this.setTvState({ playStatus_tv: 0 });
            this.audioRef_tv.pause();
        } else {
            this.setState({ playStatus: 0 });
            this.audioRef.pause();
        }
    }
    linkCommandProcess(msg: any, raw: any) {
        Util.log('linkCommandProcess: ' + JSON.stringify(msg));
        if (this.isTV()) {
            // 电视机处理逻辑
            if (msg?.cmd == 'play') {
                this.audioRef_tv.play();
            } else if (msg?.cmd == 'pause') {
                this.audioRef_tv.pause();
            } else if (msg?.cmd == 'seekto') {
                this.audioRef_tv.seekTo(msg?.position);
            } else if (msg?.cmd == 'change') {
                this.setTvState({ curPalyUrl_tv: msg?.url })
                this.audioRef_tv.setSourceUrl(msg?.url);
            }
        } else {
            if (msg?.cmd == 'tv-ready') {
                // 设置TV端相关state
                Util.log("tv-ready")
                // let a = this.state.contentObj;
                // this.setTvState({ contentObj_tv: a })
            }
        }
    }

    changePlayStatus() {
        Util.log('changePlayStatus: ', this.state.playStatus);
        if (this.state.playStatus == 0) {
            this.setState({ playStatus: 1 });
            this.audioRef.play();
            this.setTvState({ playStatus_tv: 1 });
            this.sendLinkCommand({ cmd: "play" })
        } else {
            this.setState({ playStatus: 0 });
            this.audioRef.pause();
            this.setTvState({ playStatus_tv: 0 });
            this.sendLinkCommand({ cmd: "pause" })
        }
    }
    changePlayStatus_tv() {
        Util.log('changePlayStatus_tv: ', this.state.playStatus_tv);
        if (this.state.playStatus_tv == 0) {
            this.setTvState({ playStatus_tv: 1 });
            this.audioRef_tv.play();
            this.setState({ playStatus: 1 });
            this.sendLinkCommand({ cmd: "play" })
        } else {
            this.setTvState({ playStatus_tv: 0 });
            this.audioRef_tv.pause();
            this.setState({ playStatus: 0 });
            this.sendLinkCommand({ cmd: "pause" })
        }
    }

    forward() {
        let _curPosition = 0;
        if ((this.state.position + 5) <= this.state.duration) {
            _curPosition = this.state.position + 5;
        } else {
            _curPosition = this.state.duration;
        }
        Util.log('forward:', this.state.position, _curPosition);
        this.setState({ position: _curPosition })
        this.audioRef.seekTo(_curPosition);
        this.sendLinkCommand({ cmd: "seekto", position: _curPosition })
    }
    forward_tv() {
        let _curPosition = 0;
        if ((this.state.position_tv + 5) <= this.state.duration_tv) {
            _curPosition = this.state.position_tv + 5;
        } else {
            _curPosition = this.state.position_tv;
        }
        Util.log('forward_tv:', this.state.position_tv, _curPosition);
        this.setTvState({ position_tv: _curPosition })
        this.audioRef_tv.seekTo(_curPosition);
        this.sendLinkCommand({ cmd: "seekto", position: _curPosition })
    }
    backward() {
        let _curPosition = 0;
        if ((this.state.position - 5) >= 0) {
            _curPosition = this.state.position - 5;
        } else {
            _curPosition = 0;
        }
        Util.log('backward:', this.state.position, _curPosition);
        this.setState({ position: _curPosition })
        this.audioRef.seekTo(_curPosition);
        this.sendLinkCommand({ cmd: "seekto", position: _curPosition })
    }
    backward_tv() {
        let _curPosition = 0;
        if ((this.state.position_tv - 5) >= 0) {
            _curPosition = this.state.position_tv - 5;
        } else {
            _curPosition = 0;
        }
        Util.log('backward_tv:', this.state.position_tv, _curPosition);
        this.setTvState({ position_tv: _curPosition })
        this.audioRef_tv.seekTo(_curPosition);
        this.sendLinkCommand({ cmd: "seekto", position: _curPosition })
    }

    isTV() {
        if (cooInfo.infos?.systemInfo?.os && (cooInfo.infos.systemInfo.os.indexOf('ccos') >= 0)) {
            return true;
        }
        return false;
    }
    pushToTv() {
        Util.log("lxw pushToTv");
        this.beforeLinkView();
    }
    gotoNextAudio() {
        let _curIndex = this.state.curIndex;
        if (_curIndex == this.state.playUrls.length - 1) {
            this.setState({ curIndex: 0 })
        } else {
            this.setState({ curIndex: _curIndex + 1 })
        }
        Util.log("lxw gotoNextAudio:", this.state.curIndex, this.state.playUrls[this.state.curIndex]);
        this.setState({ curPalyUrl: this.state.playUrls[this.state.curIndex] })
        this.audioRef.setSourceUrl(this.state.playUrls[this.state.curIndex]);
        this.sendLinkCommand({ cmd: "change", url: this.state.playUrls[this.state.curIndex] })
    }
    beforeLinkView() {
        coolink.protocol.isConnected().then((res) => {
            if (res.code == 0 && res.connected) {
                // 判断手机端是否连接设备
                this.startTv();
            } else {
                func.getRemoteDeviceInfos(showAutoHideToast, '设备离线中，请检查设备是否断电断网');
            }
        }).catch((err) => {
            func.getRemoteDeviceInfos(showAutoHideToast, '设备离线中，请检查设备是否断电断网');
        });
    }
    startTv() {
        let random1: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random2: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random3: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random4: string = (parseInt((Math.random() * 10000000).toString())).toString();
        coolink.protocol.sendMessage({
            "id": random1 + random2 + random3 + random4,
            "content": JSON.stringify({
                cmd: "start_tv_mini_app",
                content: JSON.stringify({
                    "mp_alias": "酷爱音乐",
                    // "mp_bundle": "https://ftp-online.skysrt.com/flie/dev/cooLink/dist_1.0.zip",
                    // "mp_bundle": "https://beta-webapp.skysrt.com/coolink/app/coo-audio/bundle_1.0.0.js",
                    "mp_bundle": "http://172.20.146.187:12345/bundle_1.0.0.js",
                    "mp_code": "coolink-mobile-applet/coo-audio",
                    "dev_name": "深圳市酷开网络科技股份有限公司",
                    "dev_type": "enterprise",
                    "mp_id": 22,
                    "mp_intro": "与大屏联动，为热爱音乐的人提供更多垂直、多元的音乐内容，与家人互动起来！",
                    "mp_logo": "https://coolink.coocaa.com/app/favicon.png",
                    "mp_name": "音乐",
                    "mp_version": "1.0.0"
                }),
            }),
            //"remoteClientID": "tv-app/com.tianci.movieplatform",
            "appTargetID": "coocaa-link-server",
            "appSourceID": "coolink-mobile-applet/coo-audio",
            "type": "TEXT",
            "extra": {},
            "reply": false,
            "broadcast": false
        } as any);
    }
    onChangeAduio = (res: any) => {
        // Util.log("lxw onChangeAduio", res.value.duration, res.value.position);
        if (res.value.duration) {
            this.setState({ duration: res.value.duration })
        }
        if (res.value.position) {
            this.setState({ position: res.value.position })
        }
    }
    onChangeAduio_tv = (res: any) => {
        // Util.log("lxw onChangeAduio_tv", res.value.duration, res.value.position);
        if (res.value.duration) {
            this.setTvState({ duration_tv: res.value.duration })
        }
        if (res.value.position) {
            this.setTvState({ position_tv: res.value.position })
        }
    }
    // 计算时间
    secondToMin(s: any) {
        var MM = Math.floor(s / 60);
        let MM_string = '';
        var SS = s % 60;
        let SS_string = '';
        if (MM < 10) {
            MM_string = "0" + MM;
        } else {
            MM_string = MM.toString();
        }
        if (SS < 10) {
            SS_string = "0" + SS;
        } else {
            SS_string = SS.toString();
        }
        let min = MM_string + ":" + SS_string;
        return min;
    }

    onEnterClicked(num: any) {
        Util.log('lxw onEnterClicked', num);
        if (num == 1) {
            this.forward_tv();
        } else if (num == 2) {
            this.changePlayStatus_tv();
        } else if (num == 3) {
            this.backward_tv();
        }
    }
    onRawKeyFocusChanged(obj: any) {
        Util.log('lxw onRawKeyFocusChanged', obj);
    }


    render() {
        const appbarHeight = ui.appbarHeight;
        const statusBarHeight = Math.round(ui.statusBarHeight);
        const bottomBarHeight = ui.bottomBarHeight;
        const clientHeight = ui.screenHeight - statusBarHeight - appbarHeight - bottomBarHeight;

        const _length = this.state.position / this.state.duration * 350;
        const _length_tv = this.state.position_tv / this.state.duration_tv * 720;
        return (
            this.isTV() ?
                <Page>
                    <Container relative={true} width={ui.screenWidth} height={ui.screenHeight} justifyContent={"center"} alignItems={'center'}>
                        <Image absolute={{ top: 0, left: 0 }} width={ui.screenWidth} height={ui.screenHeight} fit="fill" src="http://beta.webapp.skysrt.com/lxw/market/img/musicbg.jpg" alt="" ></Image>
                        <Container absolute={{ top: 0, left: 0 }} width={ui.screenWidth} height={0}>
                            <AudioView
                                ref={(e) => this.audioRef_tv = e}
                                playUrl={this.state.curPalyUrl_tv}
                                autoPlay={this.state.autoPlay_tv}
                                loopPlay={this.state.loopPlay_tv}
                                onChange={this.onChangeAduio_tv}
                            >
                            </AudioView>
                        </Container>
                        <Container relative={true} absolute={{ top: 480, left: 0 }} height={240} width={ui.screenWidth}>
                            <Center absolute={{ top: 90, left: 0 }} height={60} width={ui.screenWidth}>
                                <Container row height={60} width={200}>
                                    <Center height={60} width={60}>
                                        <Container onEnterClicked={() => this.onEnterClicked(1)} onRawKeyFocusChanged={this.onRawKeyFocusChanged.bind(this)} hasDecoration={true}>
                                            <Image height={40} width={40} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/backward.png'></Image>
                                        </Container>
                                    </Center>
                                    <Center height={60} width={80} onEnterClicked={() => this.onEnterClicked(2)} onRawKeyFocusChanged={this.onRawKeyFocusChanged.bind(this)} hasDecoration={true} requestFocus={true}>
                                        {this.state.playStatus_tv == 0 && <Image height={60} width={60} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/play.png'></Image>}
                                        {this.state.playStatus_tv == 1 && <Image height={60} width={60} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/stop1.png'></Image>}
                                    </Center>
                                    <Center height={60} width={60} >
                                        <Container onEnterClicked={() => this.onEnterClicked(3)} onRawKeyFocusChanged={this.onRawKeyFocusChanged.bind(this)} hasDecoration={true}>
                                            <Image height={40} width={40} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/forward.png'></Image>
                                        </Container>
                                    </Center>
                                </Container>
                            </Center>
                            <Center absolute={{ top: 180, left: 0 }} height={60} width={ui.screenWidth}>
                                <Container row height={60} width={720}>
                                    <Center height={60} width={60}>
                                        <Text color={Colors.White}>{this.secondToMin(this.state.position_tv)}</Text>
                                    </Center>
                                    <Center height={60} width={600}>
                                        <Container height={4} width={600} backgroundColor={Colors.Lightgray} borderRadius={10}>
                                            <Container height={4} width={_length_tv} backgroundColor={Colors.Red}></Container>
                                        </Container>
                                    </Center>
                                    <Center height={60} width={60}>
                                        <Text color={Colors.White}>{this.secondToMin(this.state.duration_tv)}</Text>
                                    </Center>
                                </Container>
                            </Center>
                        </Container>
                    </Container>
                </Page >
                :
                <Page
                    appBar={<AppBar title={'酷爱音乐'} backgroundColor={Colors.White} elevation />}
                    backgroundColor={Colors.Pagebg}
                    onHide={() => this.onHide()}
                    onShow={() => this.onShow()}
                    onPause={() => this.onPause()}
                    onResume={() => this.onResume()}
                >
                    <Container relative={true} width={ui.screenWidth} height={clientHeight}>
                        <Image absolute={{ top: 0, left: 0 }} fit="fill" src='https://beta-webapp.skysrt.com/wangyong/luckywheel/pages/wheelpageBg.png' height={ui.screenHeight} width={ui.screenWidth}></Image>
                        <Container absolute={{ top: 0, left: 0 }} width={ui.screenWidth} height={0} justifyContent={"center"} alignItems={'center'}>
                            <AudioView
                                ref={(e) => this.audioRef = e}
                                playUrl={this.state.curPalyUrl}
                                autoPlay={this.state.autoPlay}
                                loopPlay={this.state.loopPlay}
                                onChange={this.onChangeAduio}
                            >
                            </AudioView>
                        </Container>
                        <Container relative={true} absolute={{ top: 150, left: 0 }} height={px(450)} width={ui.screenWidth}>
                            <Center absolute={{ top: 0, left: 0 }} height={px(240)} width={ui.screenWidth}>
                                <Image height={px(240)} width={px(330)} fit="fill" src={this.state.audiobgImgs[this.state.curIndex]}></Image>
                            </Center>
                            <Center absolute={{ top: px(90), left: 0 }} height={px(60)} width={ui.screenWidth}>
                                <Container row height={px(60)} width={px(200)}>
                                    <Center height={px(60)} width={px(60)}>
                                        <Container onTap={() => this.backward()}>
                                            <Image height={px(40)} width={px(40)} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/backward.png'></Image>
                                        </Container>
                                    </Center>
                                    <Center height={px(60)} width={px(80)} onTap={() => this.changePlayStatus()}>
                                        {this.state.playStatus == 0 && <Image height={px(60)} width={px(60)} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/play.png'></Image>}
                                        {this.state.playStatus == 1 && <Image height={px(60)} width={px(60)} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/stop1.png'></Image>}
                                    </Center>
                                    <Center height={px(60)} width={px(60)} >
                                        <Container onTap={() => this.forward()}>
                                            <Image height={px(40)} width={px(40)} fit="fill" src='https://beta-webapp.skysrt.com/lxw/market/img/forward.png'></Image>
                                        </Container>

                                    </Center>
                                </Container>
                            </Center>
                            <Center absolute={{ top: px(180), left: 0 }} height={px(60)} width={ui.screenWidth}>
                                <Container row height={px(60)} width={px(330)}>
                                    <Center height={px(60)} width={px(40)}>
                                        <Text color={Colors.White}>{this.secondToMin(this.state.position)}</Text>
                                    </Center>
                                    <Center height={px(60)} width={px(250)}>
                                        <Container height={px(4)} width={px(250)} backgroundColor={Colors.Lightgray} borderRadius={px(10)}>
                                            <Container height={px(4)} width={px(_length)} backgroundColor={Colors.Red}></Container>
                                        </Container>
                                    </Center>
                                    <Center height={px(60)} width={px(40)}>
                                        <Text color={Colors.White}>{this.secondToMin(this.state.duration)}</Text>
                                    </Center>
                                </Container>
                            </Center>
                            <Center absolute={{ top: px(250), left: 0 }} height={px(60)} width={ui.screenWidth}>
                                <Container
                                    width={px(270)}
                                    height={px(56)}
                                    borderRadius={px(25)}
                                    justifyContent="center"
                                    alignItems="center"
                                    backgroundGradient={this.state.backgroundGradient as any}
                                    boxShadow={this.state.boxShadow}
                                    onTap={() => this.pushToTv()}
                                >
                                    <Text text="电视联动" color={0xffffffff} size={px(20)}></Text>
                                </Container>
                            </Center>
                            <Center absolute={{ top: px(320), left: 0 }} height={px(60)} width={ui.screenWidth}>
                                <Container
                                    width={px(270)}
                                    height={px(56)}
                                    borderRadius={px(25)}
                                    justifyContent="center"
                                    alignItems="center"
                                    backgroundGradient={this.state.backgroundGradient as any}
                                    boxShadow={this.state.boxShadow}
                                    onTap={() => this.gotoNextAudio()}
                                >
                                    <Text text="下一首" color={0xffffffff} size={px(20)}></Text>
                                </Container>
                            </Center>
                        </Container>
                    </Container>
                </Page >
        )
    }
}


